<template>
  <div class="app-container">
    <div class="pageContent bgFF">
      <div class="pageContentTop pageFlex pageSpaceBetween">
        <div class="itemBox" :class="{'active': step >= 1}" @click="handleStep(1)">
          填写出库信息
          <div class="sanBox"></div>
        </div>
        <div class="itemBox" :class="{'active': step >= 2}" @click="handleStep(2)">
          填写领用信息
          <div class="whiteSanBox"></div>
          <div class="sanBox"></div>
        </div>
        <div class="itemBox" :class="{'active': step >= 3}" @click="handleStep(3)">
          填写配送信息(可跳过)
          <div class="whiteSanBox"></div>
          <div class="sanBox"></div>
        </div>
        <div class="itemBox" :class="{'active': step >= 4}" @click="handleStep(4)">
          填写商品信息
          <div class="whiteSanBox"></div>
          <div class="sanBox"></div>
        </div>
        <div class="itemBox" :class="{'active': step >= 5}" @click="handleStep(5)">
          完成出库
          <div class="whiteSanBox"></div>
        </div>
      </div>
      <el-form class="formBox" ref="formRef" :model="form" :rules="rules" label-width="200">
        <div class="normalBox" v-if="step === 1">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">出库信息</div>
          </div>
          <div class="contentBox bgFF">
            <el-form-item prop="exitVoucherNo">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>出库凭证编号</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="出库凭证编号即出库单的图片"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <el-input
                  class="inputBox"
                  v-model="form.exitVoucherNo"
                  placeholder="请输入出库凭证编号"
                  clearable
              />
            </el-form-item>
            <el-form-item label="出库凭证" prop="exitVoucher">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>出库凭证</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="出库凭证即出库单的图片"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <div class="imgBox">
                <ImageUpload v-model="form.exitVoucher" bg="#FFFFFF"></ImageUpload>
              </div>
            </el-form-item>
            <el-form-item label="出库说明" prop="notes">
              <el-input
                  class="textareaBox"
                  v-model="form.notes"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入出库说明"
              />
            </el-form-item>
          </div>
          <div class="line"></div>
          <div class="dataManageBottom pageFlex pageFlexCenter">
            <el-button type="primary" @click="handleStep(1)">上一步</el-button>
            <el-button type="primary" @click="handleStep()">下一步</el-button>
          </div>
        </div>
        <div class="normalBox" v-if="step === 2">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">领用信息</div>
          </div>
          <div class="contentBox bgFF">
            <el-form-item label="领用人" prop="receivedName">
              <div class="valueBox pageFlex pageAlignCenter" @click="showTableModal('receivedName')">
                <el-text class="value">{{ form.receivedName || '请选择领用人' }}</el-text>
                <el-icon><ArrowRight /></el-icon>
              </div>
            </el-form-item>
            <el-form-item label="领用说明" prop="receivedRemarks">
              <el-input
                  class="textareaBox"
                  v-model="form.receivedRemarks"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入领用说明"
              />
            </el-form-item>
            <el-form-item prop="receivedVoucherNo">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>领用凭证编号</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="领用凭证编号即领用单单号"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <el-input
                  class="inputBox"
                  v-model="form.receivedVoucherNo"
                  placeholder="请输入领用凭证编号"
                  clearable
              />
            </el-form-item>
            <el-form-item label="领用凭证" prop="receivedVoucher">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>领用凭证</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="领用凭证即领用单的图片"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <div class="imgBox">
                <ImageUpload v-model="form.receivedVoucher" bg="#FFFFFF"></ImageUpload>
              </div>
            </el-form-item>
          </div>
          <div class="line"></div>
          <div class="dataManageBottom pageFlex pageFlexCenter">
            <el-button type="primary" @click="handleStep(2)">上一步</el-button>
            <el-button type="primary" @click="handleStep()">下一步</el-button>
          </div>
        </div>
        <div class="normalBox" v-if="step === 3">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">配送信息</div>
          </div>
          <div class="contentBox bgFF">
            <el-form-item label="配送人" prop="deliveryName">
              <div class="valueBox pageFlex pageAlignCenter" @click="showTableModal('deliveryName')">
                <el-text class="value">{{ form.deliveryName || '请选择配送人' }}</el-text>
                <el-icon><ArrowRight /></el-icon>
              </div>
            </el-form-item>
            <el-form-item label="配送说明" prop="deliveryRemarks">
              <el-input
                  class="textareaBox"
                  v-model="form.deliveryRemarks"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入配送说明"
              />
            </el-form-item>
            <el-form-item prop="deliveryVoucherNo">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>配送凭证编号</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="配送凭证编号即配送单单号"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <el-input
                  class="inputBox"
                  v-model="form.deliveryVoucherNo"
                  placeholder="请输入配送凭证编号"
                  clearable
              />
            </el-form-item>
            <el-form-item label="配送凭证" prop="deliveryVoucher">
              <template #label="e">
                <div class="pageFlex pageAlignCenter">
                  <el-text>配送凭证</el-text>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="配送凭证即配送单的图片"
                    placement="bottom"
                  >
                    <el-icon style="color: var(--el-color-primary);cursor: pointer;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <div class="imgBox">
                <ImageUpload v-model="form.deliveryVoucher" bg="#FFFFFF"></ImageUpload>
              </div>
            </el-form-item>
          </div>
          <div class="line"></div>
          <div class="dataManageBottom pageFlex pageFlexCenter">
            <el-button type="primary" @click="handleStep(3)">上一步</el-button>
            <el-button type="primary" @click="handleStep()">下一步</el-button>
          </div>
        </div>
        <div class="normalBox" v-if="step === 4">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">商品信息</div>
            <el-text>(若需填写配送数量，请先完成配送信息填写)</el-text>
          </div>
          <div class="contentBox bgFF" style="padding: 20px;">
            <el-row :gutter="10">
              <el-col :span="1.5">
                <div class="normalBtn pageFlex pageFlexCenter" @click="showTableModal('chooseGood')">
                  <img src="@/assets/images/plus.png" class="normalBtn_icon">
                  <div class="normalBtn_text">添加商品</div>
                </div>
              </el-col>
              <el-col :span="1.5">
                <div class="normalBtn pageFlex pageFlexCenter" @click="initData()">
                  <el-icon class="normalBtn_icon2"><Refresh /></el-icon>
                  <div class="normalBtn_text">刷新</div>
                </div>
              </el-col>
              <el-col :span="1.5">
                <div class="normalBtn pageFlex pageFlexCenter" :class="{'disabled': !curCheckedList.length}" @click="handleDelete()">
                  <el-icon class="normalBtn_icon2"><Delete /></el-icon>
                  <div class="normalBtn_text">删除所选商品</div>
                </div>
              </el-col>
            </el-row>
            <el-table
              v-loading="loading"
              :data="dataList"
              border
              style="margin-top: 10px;"
              @selection-change="handleCurChecked">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column prop="id" label="商品ID" width="100" :show-overflow-tooltip="true" fixed="left"></el-table-column>
              <el-table-column prop="goodsNo" label="商品编码" width="180" :show-overflow-tooltip="true" fixed="left"></el-table-column>
              <el-table-column prop="name" label="商品名称" width="180" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="stock" label="库存数量" width="160" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="出库数量" width="160">
                <template #default="scope">
                  <el-input type="number" :min="1" v-model="scope.row.number" style="width: 135px" placeholder="请输入出库数量" clearable/>
                </template>
              </el-table-column>
              <el-table-column label="领用数量" width="160">
                <template #default="scope">
                  <el-input type="number" :min="1" v-model="scope.row.receivedNumber" style="width: 135px" placeholder="请输入领用数量" clearable/>
                </template>
              </el-table-column>
              <el-table-column label="配送数量" width="160">
                <template #default="scope">
                  <el-input type="number" :min="1" :disabled="!form.deliveryId" v-model="scope.row.deliveryNumber" style="width: 135px" placeholder="请输入配送数量" clearable/>
                </template>
              </el-table-column>
              <template #empty>
                <el-empty description="暂未选择商品，请先进行选择"/>
              </template>
            </el-table>
          </div>
          <div class="line"></div>
          <div class="dataManageBottom pageFlex pageFlexCenter">
            <el-button type="primary" @click="handleStep()">下一步</el-button>
          </div>
        </div>
        <div class="normalBox" v-show="step === 5">
          <div class="titleBox pageFlex pageAlignCenter">
            <div class="line"></div>
            <div class="title">确认信息并出库</div>
          </div>
          <div class="contentBox bgFF">
            <el-result
                icon="success"
                title="提示"
                sub-title="请确认前面步骤的内容都填写完毕且信息无误后，点击下方提交按钮即可出库"
            >
              <template #extra>
                <div class="dataManageBottom pageFlex pageFlexCenter">
                  <el-button type="primary" @click="handleStep(3)">上一步</el-button>
                  <el-button type="primary" :loading="submitLoading" @click="submitNow">提交</el-button>
                </div>
              </template>
            </el-result>
          </div>
        </div>
      </el-form>
    </div>
    <el-dialog v-model="chooseGoodShow" title="选择商品" width="1000">
      <div class="tableModalBox" v-if="chooseGoodShow">
        <div class="tableModalBox_top pageFlex pageAlignCenter">
          <div class="line"></div>
          <div class="title">请进行选择</div>
        </div>
        <div class="searchBox">
          <el-form :model="chooseGoodParams" ref="chooseGoodTableModal" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="chooseGoodParams.name"
                  placeholder="请输入商品名查询"
                  clearable
                  @keyup.enter="handleTableModalQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleTableModalQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetTableModalQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="tableBox" v-if="chooseGoodShow">
          <el-table
              ref="chooseGoodTableRef"
              v-loading="chooseGoodLoading"
              :data="chooseGoodDataList"
              height="400"
              border
              @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" :selectable="setSelectable" />
            <el-table-column prop="id" label="商品ID" width="100" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="goodsNo" label="商品编码" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="name" label="商品名称" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="cover" label="商品图片" width="80" align="center">
              <template #default="scope">
                <div class="tableImgBox1">
                  <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)" v-if="scope.row.cover" />
                  <div class="emptyBox" v-else>暂无图标</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="barCode" label="商品条码" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="市场参考价" width="150" :show-overflow-tooltip="true">
              <template #default="scope">
                <div style="max-width: 120px;font-weight: 500;" class="textOverflow1">￥{{scope.row.price}}</div>
              </template>
            </el-table-column>
            <el-table-column label="采购成本价" width="150" :show-overflow-tooltip="true">
              <template #default="scope">
                <div style="max-width: 120px;font-weight: 500;" class="textOverflow1">￥{{scope.row.costPrice}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="150" :show-overflow-tooltip="true"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据"/>
            </template>
          </el-table>
          <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{chooseGoodTotal}} 条</div>
            <el-pagination background layout="sizes, prev, pager, next" :total="chooseGoodTotal" :current-page="chooseGoodParams.pageNum" :page-size="chooseGoodParams.pageSize"
                           @current-change="handleTablePageChange" @size-change="handleTableSizeChange"/>
          </div>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button @click="clearTableModalChoose">清空当前选择</el-button>
          <el-button type="primary" :disabled="!chooseGoodCheckedList.length" @click="confirmTableModalChoose">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="receivedShow" :title="receivedTitle" width="728">
      <div class="tableModalBox" v-if="receivedShow">
        <div class="tableModalBox_top pageFlex pageAlignCenter">
          <div class="line"></div>
          <div class="title">请进行选择</div>
        </div>
        <div class="searchBox">
          <el-form :model="receivedParams" ref="receivedTableModal" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="receivedParams.name"
                  placeholder="请输入用户名查询"
                  clearable
                  @keyup.enter="handleTableModalQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleTableModalQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetTableModalQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="tableBox">
          <el-table
              ref="receivedTableRef"
              v-loading="receivedLoading"
              :data="receivedDataList"
              border
              height="400"
              @select="handleTableModalSelect"
              @select-all="handleTableModalAll">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="userId" label="用户ID" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="userName" label="用户名" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="phonenumber" label="手机号" width="120" :show-overflow-tooltip="true"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{receivedTotal}} 条</div>
            <el-pagination background layout="prev, pager, next" :total="receivedTotal" :current-page="receivedParams.pageNum" :page-size="receivedParams.pageSize" @current-change="handleTablePageChange"/>
          </div>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button @click="clearTableModalChoose">清空当前选择</el-button>
          <el-button type="primary" :disabled="!receivedCur" @click="confirmTableModalChoose">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="deliveryShow" :title="deliveryTitle" width="728">
      <div class="tableModalBox" v-if="deliveryShow">
        <div class="tableModalBox_top pageFlex pageAlignCenter">
          <div class="line"></div>
          <div class="title">请进行选择</div>
        </div>
        <div class="searchBox">
          <el-form :model="deliveryParams" ref="deliveryTableModal" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="deliveryParams.name"
                  placeholder="请输入用户名查询"
                  clearable
                  @keyup.enter="handleTableModalQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleTableModalQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetTableModalQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="tableBox">
          <el-table
              ref="deliveryTableRef"
              v-loading="deliveryLoading"
              :data="deliveryDataList"
              border
              height="400"
              @select="handleTableModalSelect"
              @select-all="handleTableModalAll">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="userId" label="用户ID" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="userName" label="用户名" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="phonenumber" label="手机号" width="120" :show-overflow-tooltip="true"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{deliveryTotal}} 条</div>
            <el-pagination background layout="prev, pager, next" :total="deliveryTotal" :current-page="deliveryParams.pageNum" :page-size="deliveryParams.pageSize" @current-change="handleTablePageChange"/>
          </div>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button @click="clearTableModalChoose">清空当前选择</el-button>
          <el-button type="primary" :disabled="!deliveryCur" @click="confirmTableModalChoose">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import ImageUpload from '@/views/gasManage/components/ImageUpload';
import { searchGoodsApi } from '@/api/gasManage/stockManage/goodInfo';
import { addInventoryRecordApi } from '@/api/gasManage/stockManage/inventoryHistory';
import { listUser } from "@/api/system/user";
import {ElMessageBox, ElLoading} from "element-plus";
const { proxy } = getCurrentInstance();
const curCheckedList = ref([]);
function handleCurChecked(e){
  curCheckedList.value = e;
}
function handleDelete(){
  ElMessageBox.confirm(`确认删除数据?`,'提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteNow();
  }).catch(() => {})
}
function deleteNow(){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  if(dataList.value.length === curCheckedList.value.length){
    dataList.value = [];
  }else{
    curCheckedList.value.forEach(item=>{
      let index = dataList.value.findIndex(data=>data.id === item.id);
      dataList.value.splice(index,1);
    })
  }
  toolsDataStore.updateBatchInventoryCount(dataList.value);
  toolsDataStore.updateIsHandleInventoryCount(false);
  loading.close();
}
// -----------------------------------设置步骤---------------------------------
let step = ref(1);
function handleStep(num){
  if(num < step.value){
    stepChange(num);
  }else{
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        if(step.value === 4){
          if(dataList.value.length){
            let flag = false;
            for(let i=0;i<dataList.value.length;i++){
              let data = dataList.value[i];
              flag = scanValueError(data);
              if(!flag){
                break;
              }
            }
            if(flag){
              stepChange(num)
            }
          }else{
            proxy.$modal.msgError('您还未选择任何商品！')
          }
        }else{
          stepChange(num)
        }
      }else{
        proxy.$modal.msgError('填写内容有误！请检查');
      }
    })
  }

}
function stepChange(num){
  if(num){
    step.value = num;
  }else{
    step.value++;
  }
}
// ----------------------------------出库----------------------------------------
const form = ref({
  operationType: 1,
  exitVoucher: '',
  exitVoucherNo: '',
  notes: '',
  receivedId: '',
  receivedMobile: '',
  receivedName: '',
  receivedRemarks: '',
  receivedVoucher: '',
  receivedVoucherNo: '',
  deliveryId: '',
  deliveryMobile: '',
  deliveryName: '',
  deliveryRemarks: '',
  deliveryVoucher: '',
  deliveryVoucherNo: '',
});
const checkReceivedVoucher = (rule, value, callback) => {
  if(value === '' && form.value.receivedVoucherNo !== ''){
    callback(new Error('请上传领用凭证！'));
  }else{
    callback();
  }
}
const checkReceivedVoucherNo = (rule, value, callback) => {
  if(value === '' && form.value.receivedVoucher !== ''){
    callback(new Error('请输入领用凭证编号！'));
  }else{
    callback();
  }
}
const checkDeliveryVoucher = (rule, value, callback) => {
  if(value === '' && form.value.deliveryVoucherNo !== ''){
    callback(new Error('请上传配送凭证！'));
  }else{
    callback();
  }
}
const checkDeliveryVoucherNo = (rule, value, callback) => {
  if(value === '' && form.value.deliveryVoucher !== ''){
    callback(new Error('请输入配送凭证编号！'));
  }else{
    callback();
  }
}
const rules = ref({
  exitVoucher: [{ required: true, message: "请上传出库凭证", trigger: "blur" }],
  exitVoucherNo: [{ required: true, message: "出库凭证编号不能为空", trigger: "blur" }],
  receivedName: [{ required: true, message: "请选择领用人！", trigger: "blur" }],
  receivedVoucher: [{ validator: checkReceivedVoucher, trigger: 'blur'}],
  receivedVoucherNo: [{ validator: checkReceivedVoucherNo, trigger: 'blur'}],
  deliveryVoucher: [{ validator: checkDeliveryVoucher, trigger: 'blur'}],
  deliveryVoucherNo: [{ validator: checkDeliveryVoucherNo, trigger: 'blur'}],
});
const submitLoading = ref(false);
function scanValueError(data){
  if(data.number === ''){
    proxy.$modal.msgError(`【${data.id}】${data.name}的出库数量不能为空！`)
    return false;
  }
  if(Number(data.number) <= 0){
    proxy.$modal.msgError(`【${data.id}】${data.name}的出库数量不能小于0！`)
    return false;
  }
  if(data.receivedNumber === ''){
    proxy.$modal.msgError(`【${data.id}】${data.name}的领用数量不能为空！`)
    return false;
  }
  if(Number(data.receivedNumber) <= 0){
    proxy.$modal.msgError(`【${data.id}】${data.name}的领用数量不能小于0！`)
    return false;
  }
  if(form.value.deliveryId && data.deliveryNumber === ''){
    proxy.$modal.msgError(`【${data.id}】${data.name}的配送数量不能为空！`)
    return false;
  }
  if(data.deliveryNumber !== '' && Number(data.deliveryNumber) <= 0){
    proxy.$modal.msgError(`【${data.id}】${data.name}的配送数量不能小于0！`)
    return false;
  }
  return true;
}
function submitNow(){
  if(submitLoading.value) return;
  if(dataList.value.length){
    let flag = false;
    for(let i=0;i<dataList.value.length;i++){
      let data = dataList.value[i];
      flag = scanValueError(data);
      if(!flag){
        break;
      }
    }
    if(flag){
      proxy.$refs["formRef"].validate(valid=>{
        if(valid){
          submitLoading.value = true;
          let arr = [];
          dataList.value.forEach(item=>{
            let obj = {
              goodsId: item.id,
              number: Number(item.number),
              receivedNumber: Number(item.receivedNumber),
              deliveryNumber: Number(item.deliveryNumber),
              warehouseId: item.warehouseId,
              shelfId: item.shelfId,
              locationId: item.locationId
            }
            arr.push(Object.assign(obj, form.value))
          })
          addInventoryRecordApi(arr).then(() => {
            submitLoading.value = false;
            ElMessageBox.confirm(
                '商品出库成功',
                '提示',
                {
                  type: 'success',
                  icon: markRaw(CircleCheck),
                  showCancelButton: false
                }
            ).then(()=>{
              toBack();
            })
          }).catch(()=>{
            submitLoading.value = false;
          })
        }else{
          proxy.$modal.alertWarning('填写内容有误！请检查');
          submitLoading.value = false;
        }
      })
    }
  }else{
    proxy.$modal.msgError('请先选择商品后再进行出库！')
  }
}
// -----------------------------------表格弹窗通用--------------------------------------
function showTableModal(name){
  chooseGoodShow.value = false;
  receivedShow.value = false;
  deliveryShow.value = false;
  if(name === 'chooseGood'){
    chooseGoodCheckedList.value = [];
    chooseGoodShow.value = true;
  }else if(name === 'receivedName'){
    receivedShow.value = true;
    receivedTitle.value = '选择领用人';
  }else if(name === 'deliveryName'){
    deliveryShow.value = true;
    deliveryTitle.value = '选择配送人';
  }
  handleTableModalQuery();
}
function handleTableModalQuery(){
  if(chooseGoodShow.value){
    chooseGoodParams.value.pageNum = 1;
  }else if(receivedShow.value){
    receivedParams.value.pageNum = 1;
  }else if(deliveryShow.value){
    deliveryParams.value.pageNum = 1;
  }
  handleGetTableList();
}
async function handleGetTableList(){
  if(chooseGoodShow.value){
    chooseGoodLoading.value = true;
    searchGoodsApi(chooseGoodParams.value).then(res=>{
      chooseGoodTotal.value = Number(res.total);
      chooseGoodDataList.value = Array.isArray(res.rows) ? res.rows : [];
      chooseGoodLoading.value = false;
    }).catch(()=>{
      chooseGoodLoading.value = false;
      chooseGoodDataList.value = [];
    })
  }else if(receivedShow.value){
    receivedLoading.value = true;
    let res = await listUserApi(receivedParams.value);
    if(res){
      receivedTotal.value = Number(res.total);
      receivedDataList.value = Array.isArray(res.rows) ? res.rows : [];
      receivedLoading.value = false;
      if(form.value.receivedId && receivedDataList.value.length){
        let index = receivedDataList.value.findIndex(item=>item.userId === form.value.receivedId);
        if(index !== -1){
          nextTick(()=>{
            receivedCur.value = receivedDataList.value[index];
            proxy.$refs.receivedTableRef.toggleRowSelection(receivedCur.value, true);
          })
        }
      }
    }else{
      receivedLoading.value = false;
      receivedDataList.value = [];
    }
  }else if(deliveryShow.value){
    deliveryLoading.value = true;
    let res = await listUserApi(deliveryParams.value);
    if(res){
      deliveryTotal.value = Number(res.total);
      deliveryDataList.value = Array.isArray(res.rows) ? res.rows : [];
      deliveryLoading.value = false;
      if(form.value.deliveryId && deliveryDataList.value.length){
        let index = deliveryDataList.value.findIndex(item=>item.userId === form.value.deliveryId);
        if(index !== -1){
          nextTick(()=>{
            deliveryCur.value = deliveryDataList.value[index];
            proxy.$refs.deliveryTableRef.toggleRowSelection(deliveryCur.value, true);
          })
        }
      }
    }else{
      deliveryLoading.value = false;
      deliveryDataList.value = [];
    }
  }
}
function resetTableModalQuery(){
  if(chooseGoodShow.value){
    proxy.resetForm("chooseGoodTableModal");
  }else if(receivedShow.value){
    proxy.resetForm("receivedTableModal");
  }else if(deliveryShow.value){
    proxy.resetForm("deliveryTableModal");
  }
  handleTableModalQuery();
}
function handleTableModalSelect(e){
  let data = e[0];
  if(receivedShow.value){
    if(e.length > 1){
      data = e[1]
    }
    if(!data || (receivedCur.value && receivedCur.value.userId && receivedCur.value.userId === data.userId)){
      receivedCur.value = null;
      return false;
    }
    let index = receivedDataList.value.findIndex(item=>item.userId === data.userId);
    proxy.$refs.receivedTableRef.clearSelection();
    receivedCur.value = data;
    proxy.$refs.receivedTableRef.toggleRowSelection(receivedDataList.value[index], true);
  }else if(deliveryShow.value){
    if(e.length > 1){
      data = e[1]
    }
    if(!data || (deliveryCur.value && deliveryCur.value.userId && deliveryCur.value.userId === data.userId)){
      deliveryCur.value = null;
      return false;
    }
    let index = deliveryDataList.value.findIndex(item=>item.userId === data.userId);
    proxy.$refs.deliveryTableRef.clearSelection();
    deliveryCur.value = data;
    proxy.$refs.deliveryTableRef.toggleRowSelection(deliveryDataList.value[index], true);
  }
}
function handleTableModalAll(){
  if(receivedShow.value){
    proxy.$refs.receivedTableRef.clearSelection();
    receivedCur.value = null;
  }else if(deliveryShow.value){
    proxy.$refs.deliveryTableRef.clearSelection();
    deliveryCur.value = null;
  }
}
function handleTablePageChange(e){
  if(chooseGoodShow.value){
    chooseGoodParams.value.pageNum = e;
  }else if(receivedShow.value){
    receivedParams.value.pageNum = e;
  }else if(deliveryShow.value){
    deliveryParams.value.pageNum = e;
  }
  handleGetTableList();
}
function handleTableSizeChange(e){
  if(chooseGoodShow.value){
    chooseGoodParams.value.pageSize = e;
  }
  handleGetTableList();
}
function clearTableModalChoose(){
  if(chooseGoodShow.value){
    dataList.value = [];
    toolsDataStore.updateBatchInventoryCount([]);
    toolsDataStore.updateIsHandleInventoryCount(false);
    proxy.$refs.chooseGoodTableRef.clearSelection();
  }else if(receivedShow.value){
    form.value.receivedId = '';
    form.value.receivedMobile = '';
    form.value.receivedName = '';
    proxy.$refs.receivedTableRef.clearSelection();
  }else if(deliveryShow.value){
    form.value.deliveryId = '';
    form.value.deliveryMobile = '';
    form.value.deliveryName = '';
    proxy.$refs.deliveryTableRef.clearSelection();
  }
  hideTableModal();
}
function confirmTableModalChoose(){
  if(chooseGoodShow.value){
    dataList.value = dataList.value.concat(chooseGoodCheckedList.value);
    toolsDataStore.updateBatchInventoryCount(dataList.value);
    toolsDataStore.updateIsHandleInventoryCount(false);
    hideTableModal();
    initData();
  }else{
    if(receivedShow.value){
      form.value.receivedId = receivedCur.value.userId;
      form.value.receivedMobile = receivedCur.value.phonenumber;
      form.value.receivedName = receivedCur.value.userName;
    }else if(deliveryShow.value){
      form.value.deliveryId = deliveryCur.value.userId;
      form.value.deliveryMobile = deliveryCur.value.phonenumber;
      form.value.deliveryName = deliveryCur.value.userName;
    }
    hideTableModal();
  }
}
function hideTableModal(){
  if(chooseGoodShow.value){
    chooseGoodShow.value = false;
  }else if(receivedShow.value){
    receivedShow.value = false;
    receivedCur.value = null;
  }else if(deliveryShow.value){
    deliveryShow.value = false;
    deliveryCur.value = null;
  }
}
// -----------------------------------选择商品---------------------------------------
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
const chooseGoodShow = ref(false);
const chooseGoodLoading = ref(false);
const chooseGoodDataList = ref([]);
const chooseGoodCheckedList = ref([]);
const chooseGoodTotal = ref(0);
const chooseGoodParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: ''
})
function setSelectable(row){
  if(row.isEnable === 0){
    return false
  }else{
    let index = dataList.value.findIndex(item=>item.id === row.id);
    return index === -1;
  }
}
function handleSelectionChange(e){
  chooseGoodCheckedList.value = e;
}
// -----------------------------------选择领用人--------------------------------------
const receivedShow = ref(false);
const receivedLoading = ref(false);
const receivedDataList = ref([]);
const receivedTotal = ref(0);
const receivedCur = ref(null);
const receivedTitle = ref('');
const receivedParams = ref({
  pageNum: 1,
  pageSize: 10,
  userName: ''
});
// -----------------------------------选择配送人--------------------------------------
const deliveryShow = ref(false);
const deliveryLoading = ref(false);
const deliveryDataList = ref([]);
const deliveryTotal = ref(0);
const deliveryCur = ref(null);
const deliveryTitle = ref('');
const deliveryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userName: ''
});
function listUserApi(params){
  return new Promise((resolve, reject) =>{
    listUser(params).then(res=>{
      resolve(res)
    }).catch(()=>{
      resolve(false)
    })
  })
}
// ----------------------------------初始化----------------------------------------
import {computed, nextTick, onMounted, watch} from "vue";
import { useRoute } from 'vue-router';
import useTagsViewStore from "@/store/modules/tagsView.js";
import useToolsData from '@/store/modules/tools';
import {CircleCheck} from "@element-plus/icons-vue";
const dataList = ref([]);
const useTagsView = useTagsViewStore();
const toolsDataStore = useToolsData();
const loading = ref(false);
const routes = useRoute();
const watchRoutes = watch(routes, (newVal) => {
  let str = '/gasManage/stockManage/good-info/batchGoodsOutbound';
  if(newVal.path === str){
    handleShow();
  }else{
    let index = useTagsView.$state.visitedViews.findIndex(item=>item.path === str);
    if(index === -1){
      toolsDataStore.updateBatchInventoryCount([]);
      toolsDataStore.updateIsHandleInventoryCount(false);
      watchRoutes();
    }
  }
})
onMounted(()=>{
  handleShow();
})
function handleShow(){
  loading.value = true;
  if(toolsDataStore.$state.isHandleOutbound){
    dataList.value = toolsDataStore.$state.batchGoodsOutbound;
  }
  initData()
}
function initData(){
  loading.value = true;
  setTimeout(()=>{
    if(dataList.value.length){
      dataList.value.map(item=>{
        item.number = '';
        item.receivedNumber = '';
        item.deliveryNumber = '';
      })
    }
    loading.value = false;
  }, 500)
}
function toBack(){
  const obj = { path: "/gasManage/stockManage/goodInfo" };
  proxy.$tab.closeOpenPage(obj);
}
</script>
<style scoped lang="scss">
@import "@/assets/styles/public.scss";
.normalBtn{
  &_icon2{
    margin-right: 10px;
    color: $normalBtnColor;
  }
}
.app-container{
  width: 100%;
  background: $formBgset4;
  min-height: calc(100vh - $navBarHeight);
  .pageContent {
    width: 100%;
    min-width: 1200px;
    min-height: $pageMinHeight;
    border-radius: 6px;
    box-sizing: border-box;
    padding-top: 20px;
    .pageContentTop{
      width: calc(100% - 40px);
      height: 40px;
      margin: 20px auto 0 auto;
      box-sizing: border-box;
      .itemBox{
        width: calc((100% - 10px) / 5);
        box-sizing: border-box;
        height: 100%;
        position: relative;
        background: #F7F8FA;
        margin-right: 2px;
        font-weight: 500;
        font-size: 16px;
        color: #4E5969;
        line-height: 40px;
        box-sizing: border-box;
        padding-left: 60px;
        cursor: pointer;
        .sanBox{
          width: 28px;
          height: 28px;
          background: #F7F8FA;
          transform-origin: center center;
          transform: rotate(45deg);
          position: absolute;
          top: 6px;
          right: -14px;
          z-index: 1;
        }
        .whiteSanBox{
          width: 28px;
          height: 28px;
          background: #FFFFFF;
          transform-origin: center center;
          transform: rotate(45deg);
          position: absolute;
          top: 6px;
          left: -14px;
        }
        &:first-child{
          padding-left: 16px;
        }
        &.active{
          background: var(--el-color-primary);
          color: #FFFFFF;
          .sanBox{
            background: var(--el-color-primary);
          }
        }
      }
    }
    .formBox{
      width: 100%;
      padding: 20px;
      :deep(.el-input){
        .el-input__wrapper{
          background-color: $formBgSet;
          box-shadow: none;
        }
      }
      :deep(.el-textarea){
        .el-textarea__inner{
          background-color: $formBgSet;
          box-shadow: none;
        }
      }
      .normalBox{
        width: 100%;
        border: 1px solid $borderColor;
        .titleBox{
          width: 100%;
          height: 44px;
          background: $formBgset3;
          padding-left: 8px;
          box-sizing: border-box;
          .line{
            width: 4px;
            height: 16px;
            background: $formBgset2;
            margin-right: 8px;
          }
          .title{
            height: 16px;
            line-height: 16px;
            font-weight: 500;
            font-size: 16px;
            color: #1D2129;
          }
        }
        .contentBox{
          width: 100%;
          padding: 24px 0;
          .inputBox{
            width: 360px;
            height: 32px;
          }
          .textareaBox{
            width: 360px;
          }
          .selectOptionBox{
            width: 360px;
          }
          .valueBox{
            width: 360px;
            height: 32px;
            background-color: $formBgSet;
            padding: 0 10px;
            color: var(--el-text-color-regular);
            cursor: pointer;
            .value{
              flex: 1;
            }
          }
          .imgBox{
            min-width: 360px;
            background: $formBgSet;
            border-radius: 4px;
            padding: 12px;
            .notice{
              height: 20px;
              font-weight: 400;
              font-size: 12px;
              color: #86909C;
              line-height: 20px;
              margin-top: 12px;
            }
          }
        }
        .line{
          width: 100%;
          height: 3px;
          background-color: $formBgset4;
        }
        .dataManageBottom{
          width: 100%;
          height: 72px;
        }
      }
    }
  }
}
</style>